import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'
type Props = {
    hideInput: () => void,
    type: '' | 'name' | 'intro',
    onUpdate: (type: '' | 'name' | 'intro', value:string) => void
}
const EditInput = ({ hideInput, type, onUpdate } : Props) => {
  const refInput = useRef<InputRef>(null)
  const refTextArea = useRef<TextAreaRef>(null)

  useEffect(() => {
    if (refInput.current) {
      refInput.current.focus()
    }
    if (refTextArea.current) {
      refTextArea.current.focus()

      // refTextArea.current.setSelectionRange()
      const res = document.querySelector('.textarea textarea') as HTMLTextAreaElement
      if (res) {
        res.setSelectionRange(-1, -1)
      }
    }
  }, [])
  const userProfile = useSelector((state:RootState) => state.profile.userProfile)

  // value用来保存用户的输入
  const [value, setValue] = useState(type === 'intro' ? (userProfile.intro || '') : userProfile.name)

  return (
    <div className={styles.root}>
      <NavBar
        onBack={hideInput}
      className="navbar" right={<span className="commit-btn" onClick={() => onUpdate(type, value)}>提交</span>}>
        编辑 {type === 'name' ? '昵称' : '简介' }
      </NavBar>

      <div className="edit-input-content">
        <h3>{type === 'name' ? '昵称' : '简介'} {value}</h3>

        { type === 'name' && <div className="input-wrap">
            <Input ref={refInput} placeholder="请输入" value={value} onChange={str => setValue(str)}/></div>
        }

        { type === 'intro' && <TextArea
            ref={refTextArea}
            showCount
            maxLength={30}
            className="textarea" value={value} onChange={str => setValue(str)} /> }

      </div>
    </div>
  )
}

export default EditInput
